<template>
  <div class="home">
    <HomeHeader :category="category" @change="change"></HomeHeader>
    <div class="home-slide">
      <cube-slide :data="slides" />
    </div>
    <div class="home-title">珠峰课程</div>

    <div class="home-list">
      <cube-recycle-list
        class="list"
        :size="size"
        :on-fetch="onFetch"
        :offset="offset"
        ref ="lists"
      >
        <template slot="item" slot-scope="{ data }">
          <div :id="data.id" class="item">
              <h2>{{data.title}}</h2>
              <img :src="data.pic">
              <p>劲爆价格：{{data.price}}</p>
          </div>
        </template>
      </cube-recycle-list>
    </div>
  </div>
</template>
<script>
import HomeHeader from "@/views/Home/HomeHeader.vue";
import { createNamespacedHelpers } from "vuex";
const { mapState, mapActions ,mapMutations} = createNamespacedHelpers("home");
import {fetchList} from '@/api/home'
export default {
  components: {
    HomeHeader,
  },
  data() {
    return {
      size: 5,// 用来控制一次渲染多少条数据
      offset: 10,//配置底部拉取数据的距离
      offsetIndex:0,//每次拿到的数据的开始的索引
      hasMore:true
    }
  },
  mounted() {
    this.setCategory();
    this.setSlides();
  },
  computed: {
    ...mapState(["category", "slides"]),
  },
  methods: {
    ...mapMutations(['setLession']),
    ...mapActions(["setCategory", "setSlides"]),
    change(value) {
        this.setLession(value)
        this.hasMore = true;
        this.offsetIndex = 0;
        this.$refs.lists.reset();
    },
    async onFetch(){//函数的返回值必须是一个 Promise
        if(this.hasMore){
            let {hasMore,result} = await fetchList(this.size,this.offsetIndex);
            this.hasMore = hasMore;
            this.offsetIndex = this.offsetIndex + result.length;
            return result
        }else{
            return false;//停止滚动
        }
    }
  },
};
</script>
<style lang="less">
img {
  display: block;
  width: 100%;
  height: 100%;
}
.home {
  .home-slide {
    height: 150px;
  }
  &-title{
    font-weight: bold;
    line-height: 35px;
  }
  &-list{
      height: calc(100vh - 310px);
      width: 90%;
      margin: 10px auto 0;
      .item{
          border:2px solid#ccc;
          border-radius: 10px;
          margin-bottom: 10px;
           h2, p {
            text-align: center;
            line-height: 30px;
         }
      }
  }
}
</style>